<template>
  <div
    class="menu-item"
    :style="{ paddingLeft: level * 20 + 'px' }"
  >
    <!-- 顶级/子级菜单复选框 -->
    <el-checkbox
      :label="menu.name"
      :model-value="checkedMenuIds.includes(menu.id)"
      @change="onMenuChange($event, menu)"
    >
      {{ menu.name }}
    </el-checkbox>

    <!-- 权限按钮 -->
    <div v-if="menu.permissions && menu.permissions.length > 0" class="permissions">
      <el-checkbox-group
        :model-value="checkedPermissionMap[menu.id] || []"
        @change="onPermissionChange($event, menu.id)"
      >
        <el-checkbox
          v-for="p in menu.permissions"
          :key="p.id"
          :label="p.id"
        >
          {{ p.name }}
        </el-checkbox>
      </el-checkbox-group>

    </div>

    <!-- 子菜单（递归调用） -->
    <div v-if="menu.children && menu.children.length > 0" class="children">
      <MenuItem
        v-for="child in menu.children"
        :key="child.id"
        :menu="child"
        :level="level + 1"
        :checkedMenuIds="checkedMenuIds"
        :checkedPermissionMap="checkedPermissionMap"
        @update:checkedMenuIds="updateMenuIds"
        @update:checkedPermissionMap="updatePermissionMap"
      />
    </div>
  </div>
</template>

<script setup>
import { defineProps, defineEmits } from "vue";

const props = defineProps({
  menu: { type: Object, required: true },
  level: { type: Number, default: 0 },
  checkedMenuIds: { type: Array,require:true },
  checkedPermissionMap: { type: Object, require:true }
});

const emit = defineEmits([
  "update:checkedMenuIds",
  "update:checkedPermissionMap"
]);

// 勾选菜单时触发（支持递归子菜单）
const onMenuChange = (checked, menu) => {
  if (checked) {
    addMenuId(menu);
  } else {
    removeMenuId(menu);
  }
 };


// 递归添加菜单及子菜单 ID
const addMenuId = (menu) => {
  let newIds = [...props.checkedMenuIds];

  const traverseAdd = (m) => {
    if (!newIds.includes(m.id)) {
      newIds.push(m.id);
    }
    if (m.children && m.children.length > 0) {
      m.children.forEach(traverseAdd);
    }
  }

  traverseAdd(menu);
  emit("update:checkedMenuIds", newIds);
}

// 递归移除菜单及子菜单 ID
const removeMenuId = (menu) => {
  let newIds = [...props.checkedMenuIds];

  const traverseRemove = (m) => {
    newIds = newIds.filter(id => id !== m.id);
    if (m.children && m.children.length > 0) {
      m.children.forEach(traverseRemove);
    }
  }

  traverseRemove(menu);
  emit("update:checkedMenuIds", newIds);
}
// 权限勾选
// const onPermissionChange = (values, menuId) => {
//  emit("update:checkedPermissionMap", {
//    ...props.checkedPermissionMap,
//    [menuId]: values
//  });
//};
const onPermissionChange = (values, menuId) => {
  // 拿到当前菜单已有的权限
  const current = props.checkedPermissionMap[menuId] || [];

  // 计算新的权限（Element Plus 的 values 是最新选择的数组）
  const newValues = Array.isArray(values) ? [...values] : current;

  emit("update:checkedPermissionMap", {
    ...props.checkedPermissionMap,
    [menuId]: newValues
  });
};

// 父子递归透传
const updateMenuIds = (ids) => {
  emit("update:checkedMenuIds", ids);
};

const updatePermissionMap = (map) => {
  emit("update:checkedPermissionMap", map);
};
</script>
<style scoped>
.menu-item {
  display: flex;
  flex-direction: column;   /* 垂直排布：菜单在上，权限在下 */
  align-items: flex-start;  /* 强制靠左对齐 */
  margin: 8px 0;
  padding-left: 12px;
}

.menu-item > .el-checkbox {
  align-self: flex-start;   /* 单个菜单勾选框也靠左 */
}

/* 权限横向排列 */
.permissions {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-left: 24px;   /* 缩进比菜单更深一点 */
  margin-top: 2px;
}

/* 子菜单缩进层级 */
.children {
  margin-left: 20px;   /* 每级子菜单缩进 */
  margin-top: 6px;
}

/* 右侧整体的菜单树容器，避免靠左太紧 */
.permission-tree {
  padding: 16px 20px;
}
</style>